package com.whz.gateway.handler;

import cn.hutool.core.lang.Pair;
import com.whz.gateway.common.util.GreyUtils;
import com.whz.generic.api.ApiResponseWrapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 直接处理http 请求
 *
 * @author whz
 */
public abstract class AbstractGatewayHandler implements HandlerFunction<ServerResponse> {

    @Override
    @NonNull
    public Mono<ServerResponse> handle(@NonNull ServerRequest request) {
        // 全局灰度测试
        String greyFlag = GreyUtils.greyTestRibbon(request);

        // 增加header
        ServerRequest newReq = GreyUtils.addGreyFlag(request, greyFlag);

        // 验证流程
        Pair<Boolean, String> result = handler(newReq);
        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(result.getKey()? ApiResponseWrapper.success(result.getValue()) :
                                                      ApiResponseWrapper.fail(result.getValue())));
    }

    protected abstract Pair<Boolean, String> handler(ServerRequest request);
}